#include <zemb/Socket.h>
#include <zemb/Tracer.h>
#include <zemb/FileUtil.h>
#include <zemb/StrUtil.h>
#include <zemb/ArgUtil.h>

using namespace zemb;

class MyTcpServer : public TcpServer{
public:
    bool onNewConnection(std::unique_ptr<TcpSocket> client)
    {
        while(client)
        {
            char buf[64]={0};
            int rc=client->recvData(buf, sizeof(buf)-1,5000000);
            if (rc>0)
            {
                TRACE_DBG_CLASS("server recv:[%s]",buf); 
            }
            else if (rc<0)
            {
                TRACE_ERR_CLASS("server recv error: %d.",rc);
                continue;
            }
            else/* 客户端已断开连接 */
            {
                return true;
            }
        }
    }   
};

int main(int argc, char* argv[])
{
	std::string argValue;
	ArgOption  option;
	uint16 port=5555;
	std::string ip = "0.0.0.0";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();

	if(!option.parseArgs(argc,argv))	/* 解析参数 */
	{
		return RC_ERROR;
	}
	if(option.hasOption("h")>=0)
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("tcp server help:");
		TRACE_YELLOW("%s [-h] [-p port] [-i ip]",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help");
		TRACE_YELLOW("        -p  server port");
		TRACE_YELLOW("        -i  server ip");
		return RC_OK;
	}

	if(option.hasOption("p")>0)
	{
		port = (uint16)std::stoi(option.getValue("p")[0]);
	}
	else
	{
		TRACE_ERR("tcp server need a port: [-p port]!");
		return RC_ERROR;
	}
	
	if(option.hasOption("i")>0)
	{
		ip = argValue;
	}

	Thread serThread;
    MyTcpServer server;
    if (!server.setup(ip,port))
    {
    	TRACE_ERR("tcp server start error: %s:%d",CSTR(ip),port);
		return RC_ERROR;
	}
    if (!serThread.start(server))
    {
    	TRACE_ERR("tcp server start error.");
		return RC_ERROR;
	}
	Thread::msleep(2000);
	TRACE_INFO("tcp server start ok: %s:%d",CSTR(ip),port);
	while(1)
	{
		Thread::msleep(2000);
	}
    return RC_OK;
}
